package com.kzd.gtgame.main

import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.BarUtils
import com.kzd.gtgame.R
import com.kzd.gtgame.app.SPSConstance
import com.kzd.gtgame.callback.AppItemDecoration
import com.kzd.gtgame.custom.setOnClickAntiShakeListener
import com.kzd.gtgame.entity.MoneyData
import com.kzd.gtgame.jetpack.vm.MoneyViewModel
import com.kzd.gtgame.main.money.*
import com.kzd.gtgame.main.money.adapter.MoneySignDayAdapter
import com.kzd.gtgame.main.money.adapter.MoneySignTagAdapter
import com.kzd.gtgame.main.money.adapter.MoneyTaskDayAdapter
import com.kzd.gtgame.main.money.adapter.MoneyTaskNewAdapter
import com.kzd.gtgame.main.popup.SystemTipsPopup
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.image.loadImage
import com.module.lemlin.image.loadCircleImage
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_main_money.*
import java.math.BigDecimal
import java.util.*

class MainMoneyFragment : OwnerViewModeFragment<MoneyViewModel>() {

    companion object {
        fun newInstance(): MainMoneyFragment {
            return MainMoneyFragment()
        }
    }

    private val mMoneySignTagAdapter = MoneySignTagAdapter()

    private val mMoneySignDayAdapter = MoneySignDayAdapter()

    private val mMoneyTaskNewAdapter = MoneyTaskNewAdapter()

    private val mMoneyTaskDayAdapter = MoneyTaskDayAdapter()

    private val mSystemTipsPopup: SystemTipsPopup by lazy {
        SystemTipsPopup(requireContext())
    }

    override fun viewModel(): MoneyViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main_money

    override fun initView() {
        BarUtils.addMarginTopEqualStatusBarHeight(flMainMoneyBar)

        pbMainMoneySignProgress.max = 10000

        rvMainMoneySignTagBody.adapter = mMoneySignTagAdapter

        rvMainMoneySignDayBody.adapter = mMoneySignDayAdapter

        rvMainMoneyTaskNewBody.apply {
            layoutManager = LinearLayoutManager(context).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
            addItemDecoration(AppItemDecoration())
        }.adapter = mMoneyTaskNewAdapter.apply {
            setOnItemChildClickListener { _, view, position ->
                val itemData = getItem(position)
                if (view.id != R.id.tvMoneyTaskNewSubmit) {
                    return@setOnItemChildClickListener
                }
                if (itemData.verify_rs == 0) when (itemData.type) {
                    "idcard" -> toAccessActivity(AccessAction.VERIFICATION)
                    "mobile" -> toAccessActivity(AccessAction.PHONE_BIND)
                    "face" -> toMineUserActivity()
                    "pet_name" -> toAccessActivity(AccessAction.SETTING_NICKNAME)
                    "share" -> viewModel.userShare(
                        requireActivity(), itemData.url,
                        title = "${getString(R.string.app_name)}--领1000元",
                        desc = "注册即享千元福利，千款手游特权"
                    )
                } else if (itemData.verify_rs == 1) {
                    viewModel.moneyTaskNewGet(itemData.type)
                }
            }
        }

        rvMainMoneyBody.adapter = mMoneyTaskDayAdapter.apply {
            setOnItemClickListener { _, _, position ->
                val itemData = getItem(position)
                val url = itemData.url
                if (!url.isNullOrEmpty()) {
                    toMineRichTextActivityUrl(title = "积分抽奖", url = url)
                } else if (itemData.type == "demoTask") {
                    toMoneyTaskPlayActivity()
                } else if (itemData.type == "points_goods") {
                    toMoneyMallListActivity()
                } else if (itemData.type == "notice") {
                    toMoneyTaskBossActivity()
                } else if (itemData.type == "experience_gold") {
                    toMoneyExperienceActivity()
                } else {
                    toMoneyTaskActivity(itemData.type)
                }
            }
        }

        tvMainMoneySignSubmit.setOnClickAntiShakeListener {
            viewModel.moneySignSubmit()
        }

        //积分记录
        tvMainMineRecord.setOnClickAntiShakeListener {
            toMineRecordBillActivity(index = 2)
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.moneyData()
    }

    override fun initViewMode() {
        viewModel.moneyDataLiveData.observe(viewLifecycleOwner, { response ->
            mslMultiStateLayout.setLoadingStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            fillData(data)
        })

        viewModel.moneySignSubmitLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            toast(response.data?.message)
            viewModel.moneyData()
        })

        viewModel.moneyTaskNewGetLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            toast(response.data?.message)
            viewModel.moneyData()
        })

        viewModel.userIsShareLiveData.observe(viewLifecycleOwner, {
            viewModel.moneyTaskAddShare()
        })

        viewModel.moneyTaskAddShareLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            viewModel.moneyData()
        })
    }

    private fun fillData(data: MoneyData) {
        mMoneySignTagAdapter.setNewInstance(data.sign.config)
        mMoneySignDayAdapter.setNewInstance(data.sign.config)
        mMoneyTaskNewAdapter.setNewInstance(data.taskNew.list)
        mMoneyTaskDayAdapter.setNewInstance(data.taskDay)
        tvMainMineSignDay.text = StringBuilder().append("已连续签到")
            .append(data.sign.sign_in).append("天")
        pbMainMoneySignProgress.progress = getProgress(data.sign.sign_in)
        tvMainMoneySignSubmit.isEnabled = data.sign.dom_sign_in != 1
        tvMainMoneySignSubmit.text = if (data.sign.dom_sign_in == 1)
            "今日已签到" else "立即签到"
        tvMainMoneyNumber.text = data.sign.points.toString()

        tvMainMoneyTaskNewCoin.text = StringBuilder().append("领取")
            .append(data.taskNew.bind_coin).append("元体验金>")
        tvMainMoneyTaskNewCoin.setOnClickAntiShakeListener {

            val message = if (data.taskNew.bind_status == 0) {
                "1：完成实名认证\n2：绑定手机号码\n完成即可成为手游试玩员,获得平台赞助的1000元试玩金"
            } else "您已成为手游试玩员"
            mSystemTipsPopup.setMessage(message)
                .showPopupWindow()
        }

        ivMainMineUserHeader.loadCircleImage(
            src = SPSConstance.userInfo?.face ?: R.mipmap.ic_test_1
        )
        ivMainMoneyBanner.loadImage(data.sign.banner.img)
        ivMainMoneyBanner.setOnClickAntiShakeListener {
            val url = data.sign.banner.url
            if (url.isNullOrEmpty())
                return@setOnClickAntiShakeListener
            toMineRichTextActivityUrl(title = "积分抽奖", url = url)
        }
    }

    private fun getProgress(day: Int): Int {
        if (day == 0) {
            return 0
        }
        val progress = when {
            day <= 2 -> 6.00 + ((day - 1) * 11.00)
            day in 3..7 -> 28.00 + ((day - 3) * (22.00 / 4))
            day in 8..15 -> 50.00 + ((day - 7) * (22.00 / 8))
            day in 16..28 -> 72.00 + ((day - 15) * (22.00 / 13))
            else -> 94.00 + ((day - 28) * (6.00 / (getCurrentMonthDay() - 28)))
        }
        val bd = BigDecimal(progress).setScale(
            (2), BigDecimal.ROUND_HALF_UP
        ).toDouble()

        return (bd * 100).toInt()
    }

    /**
     * 获取当月天数
     * */
    private fun getCurrentMonthDay(): Int {
        val a = Calendar.getInstance()
        a.set(Calendar.DATE, 1)
        a.roll(Calendar.DATE, -1)
        return a.get(Calendar.DATE)
    }

}